package com.llb666.e.shop.api.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.llb666.e.shop.domain.entity.bo.ShopCartBo;
import com.llb666.e.shop.infracore.config.RedisOperator;
import com.llb666.e.shop.infracore.constants.AppConstant;
import com.llb666.e.shop.infracore.web.BaseResponse;
import com.llb666.e.shop.infracore.web.DataResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author llb666
 */
@Tag(name = "购物车接口controller", description = "购物车接口相关的api")
@RequestMapping("shopcart")
@RestController
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShopCartController extends BaseController {

    private final RedisOperator redisOperator;

    @Operation(summary = "添加商品到购物车", description = "添加商品到购物车", method = "POST")
    @PostMapping("/add")
    public BaseResponse add(
            @RequestParam String userId, @RequestBody ShopCartBo shopCartBo) {
        if (StringUtils.isBlank(userId)) {
            return DataResponse.errorMsg("");
        }
        log.info(JSONObject.toJSONString(shopCartBo));
        // 前端用户在登录的情况下，添加商品到购物车，会同时在后端同步购物车到redis缓存
        // 购物车如果已经存在该商品，数量累加
        String shopCartJson = redisOperator.get(AppConstant.SHOP_MALL_CART + ":" + userId);
        List<ShopCartBo> shopCartList;
        if (StringUtils.isNotBlank(shopCartJson)) {
            // redis中已经有购物车了
            shopCartList = JSON.parseArray(shopCartJson, ShopCartBo.class);
            // 判断购物车中是否存在已有商品，如果有的话counts累加
            boolean isHaving = false;
            for (ShopCartBo sc : shopCartList) {
                String tmpSpecId = sc.getSpecId();
                //商品规格Id
                if (tmpSpecId.equals(shopCartBo.getSpecId())) {
                    sc.setBuyCounts(sc.getBuyCounts() + shopCartBo.getBuyCounts());
                    isHaving = true;
                }
            }
            if (!isHaving) {
                shopCartList.add(shopCartBo);
            }
        } else {
            // redis中没有购物车
            shopCartList = new ArrayList<>();
            // 直接添加到购物车中
            shopCartList.add(shopCartBo);
        }
        // 覆盖现有redis中的购物车
        redisOperator.set(AppConstant.SHOP_MALL_CART + ":" + userId, JSONObject.toJSONString(shopCartList));
        return BaseResponse.ok();
    }

    @Operation(summary = "从购物车中删除商品", description = "从购物车中删除商品", method = "POST")
    @PostMapping("/del")
    public BaseResponse del(@RequestParam String userId, @RequestParam String itemSpecId) {

        if (StringUtils.isBlank(userId) || StringUtils.isBlank(itemSpecId)) {
            return DataResponse.errorMsg("参数不能为空");
        }
        // 用户在页面删除购物车中的商品数据，如果此时用户已经登录，则需要同步删除后端redis购物车中的商品
        String shopCartJson = redisOperator.get(AppConstant.SHOP_MALL_CART + ":" + userId);
        if (StringUtils.isNotBlank(shopCartJson)) {
            // redis中已经有购物车了
            List<ShopCartBo> shopCartList = JSON.parseArray(shopCartJson, ShopCartBo.class);
            // 判断购物车中是否存在已有商品，如果有的话则删除
            for (ShopCartBo sc : shopCartList) {
                String tmpSpecId = sc.getSpecId();
                if (tmpSpecId.equals(itemSpecId)) {
                    shopCartList.remove(sc);
                    break;
                }
            }
            // 覆盖现有redis中的购物车
            redisOperator.set(AppConstant.SHOP_MALL_CART + ":" + userId, JSONObject.toJSONString(shopCartList));
        }
        return BaseResponse.ok();
    }

}
